import random
import sys

from entity import*
from player import*
from companion import*
from moveable import*
from platform import*
from QuadTree import*
from entitymanager import*
from Editor import*
from level import*
from trigger import*

class Game(object):
    def __init__(self):
        self.textures = {} #Textures for entities to draw
        self.defaultFont = pygame.font.Font(None, 30)
        self.clock = pygame.time.Clock()
        entity.textures = self.textures #Gives all entities access to all textures
        self.screenWidth = 640
        self.screenHeight = 360
        self.screen = pygame.display.set_mode((self.screenWidth, self.screenHeight))
        self.setup()
        self.fps = 0
        self.fullScreen = 0
        
    def setup(self):
        
        self.dog = 0
        self.entitymanager = entitymanager()
        self.entitymanager.game = self
        self.camera = camera(self.entitymanager, self.screenWidth, self.screenHeight) #Camera initialized to default.
        self.entitymanager.updateEntities.append(self.camera)
        self.keysdown = {'right':False, 'left':False, 'space':False, 'down':False, 'up':False}
        self.loadTextures() #TEST CODE
        self.entitymanager.textures = self.textures
        self.editor = Editor(self)
        self.entitymanager.editor = self.editor
        self.player = 0 # Basic holder for the player
        

        self.level = level(self, self.camera, self.player)

    def setupTest(self, amount):
        i = amount
        while(i > 0):
            plat1 = platform(self.entitymanager, random.random() * 40, random.random() * 40)
            plat1.moveTo(random.random() * self.screen.get_width(), random.random() * self.screen.get_height())
            plat1.setTexture()
            plat1.layer = 5 - random.random() * 10
            self.entitymanager.entities.append(plat1)
            i -= 1
        self.entitymanager.quadtree = QuadTree(0, 0, 400, 400, True)
        
        for en in self.entitymanager.entities:
            self.entitymanager.quadtree.insertEntity(en)

        self.entitymanager.entities.append(self.entitymanager.quadtree)

    def setupWallJumpTest(self): #Create original walljump environment
        plat1 = platform(self.entitymanager, 200,20) #Makes a platform with dimensions 
        plat2 = platform(self.entitymanager, 200,300)
        plat3 = platform(self.entitymanager, 200,20)
        plat2.layer = 0
        plat1.moveTo(40,500) #Moves platform to this position, same as calling plat1.rect.topleft = (40,500)
        plat2.moveTo(500,100)
        plat3.moveTo(300,400)
        plat1.setTexture() #Tells the platform to get a custom code-generated texture that fills its rect.
        plat2.setTexture()
        plat3.setTexture()
        self.entitymanager.addEntity(plat1)
        self.entitymanager.addEntity(plat2)
        self.entitymanager.addEntity(plat3)
        
        self.player = player(self.entitymanager)
        self.entitymanager.addEntity(self.player, True)
        self.camera.setFocus(self.player)
        
        moveable = moveable(self.entitymanager)
        moveable.owner = self.player
        self.entitymanager.addEntity(moveable, True)
        self.camera.setFocus(moveable)
        
        companion1 = companion(self.entitymanager)
        companion1.owner = self.player
        self.player.dog = companion1
        self.entitymanager.updateEntities.append(companion1)
        self.entitymanager.entities.append(companion1)
        companion1.setplayer(self.player)
        
        trigger = trigger()
        trigger.player = self.player
        trigger.companion = self.companion
        
        self.testLevel = level(self, self.camera, self.player)
        self.testLevel.save()

    def load(self):
        #self.level = level( self.entitymanager, self, self.camera, self.player)
        self.level.load()
        self.loadTextures()

    def loadTextures(self):
        self.textures = {}
        if(not os.path.exists('textures')):
            os.makedirs('textures')

        dirList=os.listdir('textures')

        for dir in dirList:
             pathToFile = os.path.join("textures", dir)
             try:
                self.textures[dir] = pygame.image.load(pathToFile)
                self.textures[dir].set_colorkey((0,0,0), pygame.RLEACCEL)
                self.textures[dir].convert()
             except:
                 pass
             
        x = 0


    def draw(self):
        self.screen.fill((100, 100, 255))
        self.entitymanager.draw(self.camera, self.screen)
        self.editor.draw(self.camera, self.screen)
        pygame.display.flip()
    
    def update(self, timeelapsed):
        self.entitymanager.update(timeelapsed, self.keysdown)
        self.editor.update(self.events, self.keysdown)
        self.camera.seteditmode(self.editor.inEditMode)
        self.camera.getevents(self.events)

    def input(self):
        moveSpeed = 100
        self.events = pygame.event.get()
        for event in self.events:
            if event.type == pygame.KEYDOWN:
                name = pygame.key.name(event.key)
                self.keysdown[name] = True
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                if event.key == pygame.K_f:
                    if self.fullScreen == 1:
                        pygame.display.set_mode((self.screen.get_width(),self.screen.get_height()))
                        self.fullScreen = 0
                    else:
                        pygame.display.set_mode((self.screen.get_width(),self.screen.get_height()),pygame.FULLSCREEN)
                        self.fullScreen = 1

            if event.type == pygame.KEYUP:
                name = pygame.key.name(event.key)
                self.keysdown[name] = False

            

    def run(self):
        
        self.entitymanager.fpsupdate = self.fps / 60
        if(self.entitymanager.fpsupdate == 0):
            self.entitymanager.fpsupdate = 1
        self.draw()
        self.input()
        self.update(self.fps)
        self.fps = g.clock.get_fps()
        self.clock.tick(60)
        
        print self.fps

######################## Launch Code
pygame.init()
g = Game()
g.load()
#g.setupWallJumpTest()
#g.setupTest(100)
run = True


while(run):
    g.run()



